<template>
  <div class="bigbox">
    <!-- 左侧盒子树结构 -->
    <div class="leftbox">
      <div class="select">
        <span class="text">能源类型/介质</span>
        <span class="span">
          <el-select v-model="model" placeholder="请选择" size="small">
            <el-option
            class="option"
              v-for="item in options"
              :key="item.value"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </span>
      </div>
      <div class="title">
        <template>
              <el-autocomplete
              class="inline-input"
              v-model="filterText"
              size="small"
              style="margin-bottom: 10px;width:100%"
              :fetch-suggestions="querySearch"
              placeholder="输入关键字进行过滤"
              :trigger-on-focus="true"
              value-key="name"
              :debounce='300'
              @select="handleSelect"
            ></el-autocomplete>
          </template>
          <!-- <span><button @click="addtianjia">添加</button></span> -->
      </div>
      <div class="treebox">
        <!-- 树状图区域结构 -->
        <el-tree
          :props="props"
          :load="loadNode"
          node-key="id"
          accordion
          show-checkbox
          check-strictly
          @check="handClick"
          :highlight-current="true"
          :default-checked-keys="defaultid"
          :default-expanded-keys="array"
          lazy
          @node-click="handleNodeClick"
          ref="tree"
          >
          <template slot-scope="{ node, data }">
            <span :style="{ fontSize:'14px',color:'#606266'}">
              <img :src="'data:image/png;base64,' + data.iconBase64" style="  width: 16px; height: 16px; margin-right: 5px; vertical-align: bottom;"/>
              {{ node.label }}</span>
          </template>
        </el-tree>
      </div>
    </div>
    <!-- 右侧盒子主体 -->
    <div class="rightbox">
      <!-- 导航栏 -->
      <div class="righttopbox">
        <div>
          <el-radio-group v-model="radio3" size="small">
            <el-radio-button  label="1">日</el-radio-button>
            <el-radio-button  label="2">月</el-radio-button>
            <el-radio-button  label="3">年</el-radio-button>
          </el-radio-group>
          <span>
            <el-date-picker v-if="radio3=='1'" v-model="value1" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" size="small"></el-date-picker>
            <el-date-picker v-else-if="radio3=='2'" v-model="value2" type="month" value-format="yyyy-MM" placeholder="选择月" size="small"></el-date-picker>
            <el-date-picker v-else v-model="value3" type="year" value-format="yyyy" placeholder="选择年" size="small"></el-date-picker>
          </span>
        </div>
        <div>
          <el-button size="small" @click="chongzhi">重 置</el-button>
          <el-button type="primary" size="small" @click="submit">查 询</el-button>
        </div>
      </div>

      <!-- echart/table页 -->
      <div class="rightbodybox">
        <!-- <div class="tages">
          <el-tag v-for="tag in tags" :key="tag.name" closable type="" @close="handleClose(tag)" :closable="true"> {{tag.name}}</el-tag>
        </div> -->
        <div class="title">
          <div>
            <div v-show="isshow=='table'">
              <img src="../../../../assets/energy-consumption/Basic-analysis/icon/tongji.png" alt="">
              <span>统计表</span>
            </div>
            <div v-show="isshow=='echart'&&shouech">
              <img src="../../../../assets/energy-consumption/Basic-analysis/echfyhe.png" alt="">
              <span>负荷</span>
            </div>
          </div>
          <div>
            <span><el-button type="primary" size="small" @click="exporttab">导 出</el-button></span>
            <span>
              <i :style="{color:isshow==='echart'?'#007cee':''}" @click="isshow='echart'" class="iconfont icon-zhuzhuangtutubiao"></i>
              <i :style="{color:isshow==='table'?'#007cee':''}" @click="isshow='table'" class="iconfont icon-biaoge"></i>
            </span>
          </div>
        </div>
        <div class="tablebox">
          <!-- 表格盒子 -->
          <div v-show="isshow=='table'" class="fartab">
            <TableColumn ref="tabledata"
              :tableData="tableData"
              :tableConfig="tableConfig">
            </TableColumn>
            <!-- 底部分页 -->
            <div class="fenye">
              <el-pagination
                background
                layout="prev, pager, next"
                :current-page.sync="pageobj.pageNo"
                :page-size="15"
                @current-change="getdatalist"
                :total="+totalCount">
              </el-pagination>
            </div>
          </div>
          <div class="keshihua" v-show="isshow=='echart'">
            <div v-if="shouech" class="fuherchart" ref="fuherchart"></div>
            <div>
              <img style="vertical-align: middle;margin-right: 10px;" src="../../../../assets/energy-consumption/Basic-analysis/dianliang.png" alt="">
              <span>用量</span>
            </div>
            <div :style="{ height: shouech ? '47%' : '94%' }" class="dianliangechart" ref="dianliangechart"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import elementResizeDetectorMaker from 'element-resize-detector'
import * as echarts from 'echarts'
import { exportexcel } from '@/utils/excel'
import { getdianquxianapi, getyongliangapi, gettablelistapi } from '@/api/energy-consumption/Basic-analysis/DataComparison'
import { getgenjiedianapi, getzijidianapi, getnengyuantypeapi } from '@/api/energy-consumption/Basic-information/gateway'
import { getKeywordListApi } from '@/api/Ledger3'
import TableColumn from '@/components/Table/index.vue'
export default {
  name: 'CallPoliceIndex',
  components: { TableColumn },
  data () {
    return {
      shouech: true,
      isshow: 'echart',
      value1: '',
      value3: '',
      value2: '',
      radio3: '1',
      filterText: '',
      props: {
        label: 'name',
        children: 'children',
        isLeaf: 'leaf'
      },
      array: [],
      options: [],
      model: '',
      tableData: [],
      tableConfig: [],
      tags: [],
      treevalue: {},
      pageobj: {
        pageNo: 0,
        pageSize: 15
      },
      totalCount: '',
      companyName: '',
      defaultid:[]
    }
  },

  async mounted () {
    this.gettime()
    // 获取能源介质
    const jiezhi = await getnengyuantypeapi()
    this.options = jiezhi.data.list
    this.model = jiezhi.data.list[0].code
    this.getfuheechart([])
    this.getdianliangechart([])
  },

  methods: {
    // 获取列表
    async getdatalist () {
      this.$refs.tabledata.loading = true
      // 判断类型是否为电 如果是表格加列 如果不是删除所加列
      if (this.model == '01') {
        this.tableConfig = [
          { label: '用电单位', prop: 'companyName' },
          { label: '时间', prop: 'dateTime' },
          { label: '用能单元', prop: 'unitName' },
          { label: '用量(kWh)', prop: 'usageValue' },
          { label: '负荷(kW)', prop: 'loadValue' }
        ]
      } else {
        this.tableConfig = [
          { label: '用电单位', prop: 'companyName' },
          { label: '时间', prop: 'dateTime' },
          { label: '用能单元', prop: 'unitName' },
          { label: '用量(m³)', prop: 'usageValue' }
        ]
      }
      const arr = []
      this.tags.filter(ele => {
        arr.push(ele.className + '_' + ele.id + '_' + ele.name)
      })
      const { data: { list, totalCount } } = await gettablelistapi({
        contrastString: arr.join(','),
        companyName: this.companyName,
        dateString: this.radio3 == '1' ? this.value1 : this.radio3 == '2' ? this.value2 : this.value3,
        dateType: this.radio3,
        pageNo: this.pageobj.pageNo - 1,
        energyType: this.model,
        pageSize: this.pageobj.pageSize
      })
      this.tableData = list
      this.totalCount = totalCount
      this.$refs.tabledata.loading = false
    },
    // 查询按钮
    submit () {
      if (this.tags.length) {
        // 判断类型是否为电 如果是调负荷接口生成负荷图表 如果不是就只调用量和表格的数据
        if (this.model == '01') {
          this.shouech = true
          this.getfyhelist().then(list => {
            this.getfuheechart(list)
          })
        } else {
          this.shouech = false
        }
        this.getyonlianglist().then(list => {
          this.$message.success('获取数据成功')
          this.getdianliangechart(list)
        })
        this.getdatalist()
      } else {
        this.$message.warning('请先选择设备')
        this.getdianliangechart([])
        this.getfuheechart([])
      }
    },
    // 重置
    chongzhi () {
      this.radio3 = '1'
      this.gettime()
      this.submit()
    },
    // 获取负荷曲线数据
    async getfyhelist () {
      const arr = []
      this.tags.filter(ele => {
        arr.push(ele.className + '_' + ele.id + '_' + ele.name)
      })
      const res = await getdianquxianapi({
        contrastString: arr.join(','),
        dateString: this.radio3 == '1' ? this.value1 : this.radio3 == '2' ? this.value2 : this.value3,
        dateType: this.radio3,
        energyType: this.model
      })
      return res.data.list
    },
    // 获取用量曲线数据
    async getyonlianglist () {
      const arr = []
      this.tags.filter(ele => {
        arr.push(ele.className + '_' + ele.id + '_' + ele.name)
      })
      const res = await getyongliangapi({
        contrastString: arr.join(','),
        dateString: this.radio3 == '1' ? this.value1 : this.radio3 == '2' ? this.value2 : this.value3,
        dateType: this.radio3,
        energyType: this.model
      })
      return res.data.list
    },
    // 导出
    exporttab () {
      if (this.tags.length == 0) return this.$message.warning('请先选择设备')
      const arr = []
      this.tags.filter(ele => {
        arr.push(ele.className + '_' + ele.id + '_' + ele.name)
      })
      exportexcel('ecm-microservice-biz/ecm/basic/statistics/data/contrast/exportExcel', {
        contrastString: arr.join(','),
        companyName: this.companyName,
        dateString: this.radio3 == '1' ? this.value1 : this.radio3 == '2' ? this.value2 : this.value3,
        dateType: this.radio3,
        energyType: this.model
      }, '用量数据')
    },
    // 树节点选中
    handleNodeClick (val) {
      this.treevalue = val
    },
    handClick () {
      this.tags = this.$refs.tree.getCheckedNodes(false, true)
      console.log(this.tags,55555555);
      
      this.submit()
    },
    // 添加tags
    addtianjia () {
      // 判断当前是否有选中节点 不然不允许添加
      if (!this.treevalue.id) return this.$message.warning('请先选择')
      if (!this.tags.length > 0) {
        this.tags.push(this.treevalue)
        return this.submit()
      }
      // 检查是否存在重复项
      const isDuplicate = this.tags.some(ele => ele.id == this.treevalue.id)
      // 如果不存在重复项，则将节点添加到数组中并执行 this.submit 函数
      if (!isDuplicate) {
        this.tags.push(this.treevalue)
        this.submit()
      } else {
        // 如果存在重复项，则弹出提示
        this.$message.warning('请勿重复添加')
      }
    },
    // 移除tags
    handleClose (val) {
      this.tags = this.tags.filter(ele => ele.id !== val.id)
    },
    // 树节点搜索
    async querySearch (queryString, cb) {
      setTimeout(async () => {
        const res = await getKeywordListApi({ name: queryString })
        const restaurants = res.data.list
        cb(restaurants)
      }, 500)
      // 调用 callback 返回建议列表的数据
    },
    // 搜索选择
    handleSelect (item) {
      // 拿到父节点id 添加至展开数组中用以展开选中节点的父节点
      const newarr = item.pathId.split(',')
      for (let i = 0; i < newarr.length; i++) {
        if (newarr[i]) {
          this.array.push(newarr[i])
        }
      }
      // push方法是同步任务 但是节点展开需要掉接口是异步任务 如果此时直接调用选中节点高亮方法由于节点还未完全展开所以拿不到所选中的节点信息
      // 编写递归函数根据getNode判断选中的节点是否完全展开
      function getgaoliang (that) {
        const node = that.$refs.tree.getNode(item)
        // node不为null说明节点已经完全展开 所选节点已经存在 调用方法高亮选中节点以及模拟点击该节点
        if (node) {
          that.handleNodeClick(node.data)
          that.$refs.tree.setCurrentKey(String(item.id))
        } else {
          // 如果node为null说明节点还未完全展开 继续调用函数
          setTimeout(() => {
            getgaoliang(that)
          }, 500)
        }
      }
      getgaoliang(this)
    },
    // 树结构懒加载
    async loadNode (node, resolve) {
      const res = await getgenjiedianapi({ treeModel: 'ENERGY_SET_TREE' })
      // const res = await getgenjiedianapi({ treeModel: 'ENERGY_BUILDING_SET_TREE' })
      const ress = await getzijidianapi(res.data.list[0])
      if (node.level === 0) {
        this.companyName = ress.data.list[0].name
        this.defaultid = [ress.data.list[0].id]
        this.tags = [ress.data.list[0]]
        this.submit()
        return resolve(ress.data.list)
      } else if (node.level >= 1) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      }
    },
    // 获取负荷图标
    getfuheechart (list) {
      const chartDom = this.$refs.fuherchart
      const myChart = echarts.init(chartDom)
      let option
      const timePoints = list[0]?.datalist.map(ele => ele.timeReading)
      const series = list.map(ele => {
        return {
          name: ele.name,
          data: ele.datalist.map(ele => ele.valueReading),
          type: 'line',
          showSymbol: false,
          smooth: true
        }
      })
      option = {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          top: '10%',
          left: '5%',
          right: '0%'
        },
        legend: {
          itemWidth: 12,
          itemHeight: 2,
          icon: 'rect'
        },
        xAxis: {
          type: 'category',
          data: timePoints
        },
        yAxis: {
          name: 'kW',
          type: 'value'
        },
        series: series
      }
      myChart.clear()
      option && myChart.setOption(option)
      window.addEventListener('resize', () => {
        // 图表响应处理
        myChart.resize()
      })
    },
    // 获取电量图标
    getdianliangechart (list) {
      const chartDom = this.$refs.dianliangechart
      const myChart = echarts.init(chartDom)
      let option
      const timePoints = list[0]?.datalist.map(ele => ele.timeReading)
      const series = list.map(ele => {
        return {
          name: ele.name,
          data: ele.datalist.map(ele => ele.valueReading),
          type: 'bar'
        }
      })
      option = {
        grid: {
          top: '10%',
          bottom: '7%',
          left: '5%',
          right: '0%'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          right: 'center'
        },
        xAxis: [
          {
            type: 'category',
            data: timePoints,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name:this.options.find(ele=>ele.code==this.model).unit
          }
        ],
        series: series
      }
      myChart.clear()
      option && myChart.setOption(option)
      window.addEventListener('resize', () => {
        myChart.resize()
      })
      // 根据当前容器的尺寸变化而让图表也跟着变化
      const changeSize = elementResizeDetectorMaker()
      const _this = this
      changeSize.listenTo(chartDom, () => { // chartDom为之前获取到的容器名
        _this.$nextTick(() => {
          myChart.resize()
        })
      })
    },
    // 获取当前时间戳
    gettime () {
      const date = new Date()
      const year = date.getFullYear() // 年
      const mon = date.getMonth() + 1 // 月
      const month = mon < 10 ? '0' + mon : mon
      const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate() // 日
      this.value3 = year.toString()
      this.value2 = year + '-' + month
      this.value1 = year + '-' + month + '-' + day
    }
  },
  watch: {
    filterText (newValue) {
      this.filterText = newValue.replace(/^\[(.*?)\]/, '').replace(/\((.*?)\)$/, '')
    }
  }
}
</script>

<style scoped lang="scss">
.option{
  padding-left: 10px;
}
.bigbox{
  height: 100%;
  padding: 10px;
  display: flex;
  .leftbox{
    width: 300px;
    padding: 15px;
    background-color: #fff;
    height: 100%;
    margin-right: 10px;
    .select{
      display: flex;
      align-items: center;
      .text{
        font-size: 14px;
        margin-right: 5px;
      }
      .span{
        display: inline-block;
        flex:1;
      }
    }
    .title{
      display: flex;
      justify-content: space-between;
      margin-top: 10px;
    }
  }
  .rightbox{
    width: calc(100% - 310px);
    height: 100%;
    .righttopbox{
      height: 80px;
      line-height: 80px;
      padding: 0 20px;
      background-color: #fff;
      margin-bottom: 10px;
      display: flex;
      justify-content: space-between;
      span{
        margin-left: 20px;
      }
    }
    .rightbodybox{
      height: calc(100% - 90px);
      background-color: #fff;
      padding: 20px;
      .tages{
        height: 42px;
      }
      .title{
        display: flex;
        justify-content: space-between;
        img{
          vertical-align: middle;
        }
        span{
          margin-left: 10px;
          i:hover{
            color: #2194ff;
            cursor: pointer;
          }
        }
        i{
            width: 20px;
            height: 20px;
            margin-left: 10px;
        }
      }
      .tablebox{
        height: 97%;
        margin-top: 10px;
        .fartab{
          height: 95%;
          .fenye{
            text-align: right;
            margin-top: 10px;
          }
        }
        .keshihua{
          height: 100%;
          .fuherchart{
            height: 47%;
          }
          .dianliangechart{
            height: 47%;
          }
        }
      }
    }
  }
}
::v-deep .el-divider--vertical{
  height: 100%;
}
::v-deep .el-tag--light{
  padding:  0 10px;
  margin: 0 10px 10px 0;
}
</style>